﻿<!--@时间：2022-5-5
    @描述：控件-右键菜单
    @使用：
        import ContextMenu from "@/components/common/ContextMenu.vue"
属性如下：
menuList:数据列表，格式：[{
  text: '菜单名称',
  icon: '图标名称'
}]
onMenuClick: 菜单点击事件，onMenuClick(text)
-->
<template>
  <div @contextmenu.prevent="openMenu($event)">
    <div v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
      <slot name="menu">
        <ul >
          <li v-for="(item, index) in menuList" :key="index" @click="onClick(item.text)">
            <i class = 'iconfont ' :class = 'item.icon'></i>
            <span>{{item.text}}</span>
          </li>
        </ul>
      </slot>
    </div>
    <slot></slot>
  </div>
</template>
<script>
export default {
  props: ['menuList'],
  data () {
    return {
      visible: false,
      left: 0,
      top: 0
    }
  },
  watch: {
    visible (value) {
      if (value) {
        document.body.addEventListener('click', this.closeMenu)
      } else {
        document.body.removeEventListener('click', this.closeMenu)
      }
    }
  },
  methods: {
    openMenu (e) {
      var x = e.offsetX
      var y = e.offsetY
      this.top = y
      this.left = x
      this.visible = true
    },
    closeMenu () {
      this.visible = false
    },
    onClick (text) {
      this.$emit('onMenuClick', text)
    }
  }
}
</script>
<style>
.contextmenu {
  margin: 0;
  background: #fff;
  z-index: 3000;
  position: absolute;
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 400;
  color: #333;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);
}

.contextmenu li {
  margin: 0;
  padding: 7px 16px;
  cursor: pointer;
}

.contextmenu li:hover {
  background: #eee;
}
</style>
